package org.example.library.service;

import org.example.library.dao.BookDao;
import org.example.library.vertile.Book;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class BookService {
    BookDao bookDao = new BookDao();
    public int insertBook(Book book){
        if(book.getName()==null||book.getNumber()==null||book.getAuthor()==null){
            return 0;
        }
        if(bookDao.searchBook(book.getNumber())==null){
            return -1;
        }
        return bookDao.insertBook(book);
    }

    public Book searchBook(String number){
        Book book = new Book();
        book = bookDao.searchBook(number);
        return bookDao.searchBook(book.getNumber());
    }

    public int deleteBook(String number){
        return bookDao.deleteBook(number);
    }

    public Book updateBook(String number){
        Book book = new Book();
        return bookDao.updateBook(book);
    }

    public boolean getBookFromCsv() {
        File file = null;
        FileReader reader = null;
        BufferedReader br = null;
        try {
            file = new File(this.getClass().getResource("/").toString().substring(6) + "book.csv");
            reader = new FileReader(file);
            br = new BufferedReader(reader);
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] str = line.split(",");
                if("name".equals(str[0])){
                    continue;
                }

                Book book = new Book();
                book.setName(str[0]);
                book.setAuthor(str[1]);
                book.setAuthor(str[2]);
                insertBook(book);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                if(reader != null){
                    reader.close();
                }
                if(br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
}
